﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Input;
using churchtool.Plugin.SermonUpload.ViewModel;
using churchtool.Plugin.SermonUpload.Data;
using System.Text.RegularExpressions;

namespace churchtool.Plugin.SermonUpload.Operations.Commands
{
    class SetID3TagsCommand : ICommand
    {
        #region Fields

        // Member variables
        private UploadWindowViewModel m_ViewModel;

        #endregion

        #region Constructor

        /// <summary>
        /// Default constructor.
        /// </summary>
        public SetID3TagsCommand(UploadWindowViewModel viewModel)
        {
            m_ViewModel = viewModel;
        }

        #endregion

        #region ICommand Members

        /// <summary>
        /// Whether the DoBrowseFilesCommand is enabled.
        /// </summary>
        public bool CanExecute(object parameter)
        {
            return true;
        }

        /// <summary>
        /// Actions to take when CanExecute() changes.
        /// </summary>
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        /// <summary>
        /// Executes the DoBrowseFilesCommand
        /// </summary>
        public void Execute(object parameter)
        {
            string topic = m_ViewModel.SermonTitle;
            if (topic == null)
            {
                MessageBox.Show("Please set a sermon title", "Sermon Title Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            string author = m_ViewModel.Preacher;
            if (author == null)
            {
                MessageBox.Show("Please set a sermon author", "Sermon Author Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            DateTime date = m_ViewModel.SermonDate;
            if (date == null)
            {
                date = System.DateTime.Now;
            }

            // Get file
            TagLib.File file = TagLib.File.Create(FtpConnectionSettings.GetInstance().SourceFile[0]);

            // Clear ID3v1tags
            TagLib.Id3v1.Tag id3v1Tag = file.GetTag(TagLib.TagTypes.Id3v1) as
            TagLib.Id3v1.Tag;
            id3v1Tag.Title = null;
            id3v1Tag.Performers = new string[0];
            id3v1Tag.Album = null;
            id3v1Tag.Year = 0;
            id3v1Tag.Comment = null;
            id3v1Tag.Track = 0;
            id3v1Tag.TrackCount = 0;
            id3v1Tag.Genres = new string[0];

            // Set ID3v2 tag values
            TagLib.Id3v2.Tag id3v2Tag = file.GetTag(TagLib.TagTypes.Id3v2) as
            TagLib.Id3v2.Tag;
            id3v2Tag.Title = topic;
            //id3v2Tag.Artists = author;
            id3v2Tag.Performers = new string[] { author };
            id3v2Tag.Album = "www.fcg-rv.de";
            id3v2Tag.Year = (uint)date.Year;
            id3v2Tag.Track = 1;
            id3v2Tag.TrackCount = 1;
            id3v2Tag.Genres = new string[] { "Religious" };
            id3v2Tag.Disc = 1;
            id3v2Tag.Comment = "comment";
            id3v2Tag.AlbumArtists = new string[] { author };
            id3v2Tag.Composers = new string[0]; ;
            id3v2Tag.Copyright = "www.fcg-rv.de";

            // Save
            file.Save();

            String topicFilename = RemoveSpecialCharacters(topic);
            String newName = date.ToString("yyyy-MM-dd") + "-" + topicFilename + "_" + DateTime.Now.ToString("MM-dd-yyyy_hh-mm-ss") + ".mp3";
            var fileInfo = new FileInfo(FtpConnectionSettings.GetInstance().SourceFile[0]);
            string newPath = fileInfo.Directory + "\\" + newName;
            File.Move(FtpConnectionSettings.GetInstance().SourceFile[0], newPath);
            FtpConnectionSettings.GetInstance().SourceFile[0] = newPath;

            m_ViewModel.RaiseID3TageSetEvent();
        }

        #endregion

        #region Helpers

        private string RemoveSpecialCharacters(string name)
        {
            if (name == null)
                return null;

            // Replace invalid characters with "_" char.
            name = Regex.Replace(name, @"[^\w\.-]", "_");

            string retVal = name.Replace("ä", "ae");
            retVal = retVal.Replace("ö", "oe");
            retVal = retVal.Replace("ü", "ue");
            retVal = retVal.Replace("\\", "-");
            retVal = retVal.Replace(" ", "-");
            retVal = retVal.Replace("{", "---");
            retVal = retVal.Replace("}", "---");
            return retVal;
        }

        #endregion
    }
}
